import React, { useState, useEffect } from "react";
import {
    Breadcrumb,
    Card,
    Typography,
    Form,
    Input,
    Button,
    Avatar,
    Upload,
    message,
    Space,
    Row,
    Col,
    Spin,
    Modal,
    Steps
} from "antd";
import {
    UserOutlined,
    PhoneOutlined,
    MailOutlined,
    WechatOutlined,
    CameraOutlined,
    SaveOutlined,
    ReloadOutlined,
    SafetyCertificateOutlined,
    SendOutlined
} from "@ant-design/icons";
import { getRequest, postRequest, uploadRequest } from "../../../../components/network/api";

const { Title, Paragraph, Text } = Typography;

interface PersonalInfo {
    nick_name: string;
    icon_url: string;
    phone: string;
    email: string;
    wechat_num: string | null;
}

interface VerificationModal {
    visible: boolean;
    type: 'phone' | 'email' | null;
    step: 'old' | 'new';
    oldValue: string;
    newValue: string;
}

const MyProfilePage: React.FC = () => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [submitting, setSubmitting] = useState(false);
    const [personalInfo, setPersonalInfo] = useState<PersonalInfo | null>(null);

    // 验证码相关状态
    const [verificationModal, setVerificationModal] = useState<VerificationModal>({
        visible: false,
        type: null,
        step: 'old',
        oldValue: '',
        newValue: ''
    });
    const [verificationForm] = Form.useForm();
    const [countdown, setCountdown] = useState(0);
    const [verificationLoading, setVerificationLoading] = useState(false);

    // 获取个人资料数据
    const fetchPersonalInfo = async () => {
        setLoading(true);
        try {
            const response = await getRequest("/user/displayPersonalInfo", {}, true);
            if (response.code === 200) {
                const data = response.data;
                setPersonalInfo(data);
                form.setFieldsValue({
                    nick_name: data.nick_name,
                    phone: data.phone,
                    email: data.email,
                    wechat_num: data.wechat_num || '',
                });
            } else {
                message.error(response.msg || '获取个人信息失败');
            }
        } catch (error) {
            console.error('获取个人信息失败:', error);
            message.error('获取个人信息失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    // 保存个人资料（真实接口调用）
    const handleSave = async (values: any) => {
        setSubmitting(true);
        try {
            const payload = {
                nick_name: values.nick_name,
                icon_url: personalInfo?.icon_url || '',
                phone: values.phone,
                email: values.email,
                wechat_num: values.wechat_num || ''
            };
            const response = await postRequest('/user/changePersonalInfo', payload, true);
            if (response?.code === 200) {
                message.success('个人资料保存成功！');
                // 同步本地显示，或重新拉取
                setPersonalInfo(prev => prev ? { ...prev, ...payload } : prev);
            } else {
                message.error(response?.msg || '保存失败，请稍后重试');
            }
        } catch (error: any) {
            console.error('保存个人信息失败:', error);
            message.error(error?.message || '保存失败，请稍后重试');
        } finally {
            setSubmitting(false);
        }
    };

    // 头像上传处理（使用自定义请求，走统一动态路径）
    const handleAvatarUpload = async (options: any) => {
        const { file, onSuccess, onError, onProgress } = options;
        // 本地体积校验，避免大文件直接触发网络层失败
        const maxSizeBytes = 10 * 1024 * 1024; // 10MB
        if (file && file.size > maxSizeBytes) {
            Modal.error({ title: '上传失败', content: '文件大小超出限制，请上传不超过10MB的文件' });
            onError && onError(new Error('文件大小超出限制，请上传不超过10MB的文件'));
            return;
        }
        try {
            const formData = new FormData();
            formData.append('file', file);

            const response = await uploadRequest(
                '/user/uploadPicToStorage',
                formData,
                true,
                (evt) => {
                    if (evt.total) {
                        const percent = Math.round((evt.loaded / evt.total) * 100);
                        onProgress && onProgress({ percent }, file);
                    }
                }
            );

            // 期望返回：{ code: 200, msg: 'success', data: 'https://...' }
            if (response && response.code === 200) {
                const data = response.data;
                if (typeof data === 'string' && /^https?:\/\//.test(data)) {
                    // 成功，预览更新头像地址（先让用户看到变更效果）
                    setPersonalInfo(prev => prev ? { ...prev, icon_url: data } : prev);
                    message.success('头像上传成功');
                    onSuccess && onSuccess(response, file);
                } else {
                    // data 为错误信息字符串
                    Modal.error({
                        title: '上传失败',
                        content: typeof data === 'string' ? data : '文件格式不正确或上传失败',
                    });
                    onError && onError(new Error(typeof data === 'string' ? data : '上传失败'));
                }
            } else {
                Modal.error({
                    title: '上传失败',
                    content: response?.msg || '上传失败，请稍后重试',
                });
                onError && onError(new Error(response?.msg || '上传失败'));
            }
        } catch (err: any) {
            Modal.error({ title: '上传失败', content: err?.message || '网络异常，请稍后重试' });
            onError && onError(err);
        }
    };

    // 发送验证码
    const sendVerificationCode = async (type: 'phone' | 'email', value: string, isNewValue: boolean = false) => {
        try {
            let response;

            if (isNewValue) {
                // 发送新号码/邮箱验证码（检查是否已被绑定）
                if (type === 'email') {
                    response = await getRequest(`/user/sendNewEmailDynamicCode/${value}`, {}, true);
                } else {
                    response = await getRequest(`/user/sendNewPhoneDynamicCode/${value}`, {}, true);
                }
            } else {
                // 发送旧号码/邮箱验证码
                if (type === 'email') {
                    response = await getRequest(`/user/sendEmailDynamicCode/${value}`, {}, true);
                } else {
                    response = await getRequest(`/user/sendPhoneDynamicCode/${value}`, {}, true);
                }
            }

            console.log('发送验证码响应:', response);

            if (response.code === 200) {
                if (response.msg.includes('发送成功')) {
                    message.success(`验证码已发送到${value}`);

                    // 开始倒计时
                    setCountdown(60);
                    const timer = setInterval(() => {
                        setCountdown((prev) => {
                            if (prev <= 1) {
                                clearInterval(timer);
                                return 0;
                            }
                            return prev - 1;
                        });
                    }, 1000);
                } else {
                    message.error(response.msg || '发送验证码失败');
                }
            } else if (response.code === 500) {
                // 处理已被绑定的情况
                message.error(response.msg || '该号码/邮箱已被其他用户绑定');
            } else {
                message.error(response.msg || '发送验证码失败');
            }

        } catch (error) {
            console.error('发送验证码失败:', error);
            message.error('发送验证码失败，请稍后重试');
        }
    };


    // 关闭验证弹窗
    const closeVerificationModal = () => {
        setVerificationModal({
            visible: false,
            type: null,
            step: 'old',
            oldValue: '',
            newValue: ''
        });
        verificationForm.resetFields();
        setCountdown(0);
    };

    // 验证旧号码/邮箱
    const verifyOldValue = async (values: any) => {
        setVerificationLoading(true);
        try {
            const { type, oldValue } = verificationModal;
            const { oldCode } = values;

            // 构造请求参数
            const requestData: any = {
                smsCode: oldCode
            };

            if (type === 'phone') {
                requestData.phone = oldValue;
            } else if (type === 'email') {
                requestData.email = oldValue;
            }

            console.log('验证旧值请求参数:', requestData);

            const response = await postRequest('/user/dynamicCodeCheck', requestData, true);
            console.log('验证旧值响应:', response);

            if (response.code === 200) {
                // 验证成功，进入下一步
                setVerificationModal(prev => ({
                    ...prev,
                    step: 'new'
                }));

                verificationForm.resetFields();
                setCountdown(0); // 重置倒计时，让新邮箱的发送按钮可以立即点击
                message.success('旧号码验证成功');
            } else {
                message.error(response.msg || '验证码错误，请重试');
            }

        } catch (error) {
            console.error('验证失败:', error);
            message.error('验证码错误，请重试');
        } finally {
            setVerificationLoading(false);
        }
    };

    // 验证新号码/邮箱（不保存，只更新前端显示）
    const verifyNewValue = async (values: any) => {
        setVerificationLoading(true);
        try {
            const { type, newValue } = verificationModal;
            const { newCode } = values;

            // 构造请求参数
            const requestData: any = {
                smsCode: newCode
            };

            if (type === 'phone') {
                requestData.phone = newValue;
            } else if (type === 'email') {
                requestData.email = newValue;
            }

            console.log('验证新值请求参数:', requestData);

            const response = await postRequest('/user/dynamicCodeCheck', requestData, true);
            console.log('验证新值响应:', response);

            if (response.code === 200) {
                // 验证成功，更新前端显示（不保存到后端）
                if (type === 'phone') {
                    form.setFieldsValue({ phone: newValue });
                    setPersonalInfo(prev => prev ? { ...prev, phone: newValue } : null);
                } else if (type === 'email') {
                    form.setFieldsValue({ email: newValue });
                    setPersonalInfo(prev => prev ? { ...prev, email: newValue } : null);
                }

                closeVerificationModal();
                message.success(`${type === 'phone' ? '手机号' : '邮箱'}验证成功，请点击保存按钮完成修改`);
            } else {
                message.error(response.msg || '验证码错误，请重试');
            }

        } catch (error) {
            console.error('验证失败:', error);
            message.error('验证码错误，请重试');
        } finally {
            setVerificationLoading(false);
        }
    };


    useEffect(() => {
        fetchPersonalInfo();
    }, []);

    return (
        <>
            <Breadcrumb style={{marginBottom: 12}} items={[
                { title: '首页' },
                { title: '我的' },
                { title: '个人信息' },
            ]} />

            <Card bordered>
                <Title level={4}>个人信息</Title>

                <Spin spinning={loading}>
                    <Row gutter={[24, 24]}>
                        {/* 头像区域 */}
                        <Col xs={24} sm={8} md={6}>
                            <div style={{ textAlign: 'center' }}>
                                <div style={{ marginBottom: 16 }}>
                                    <Avatar
                                        size={120}
                                        src={personalInfo?.icon_url}
                                        icon={<UserOutlined />}
                                        style={{ border: '2px solid #f0f0f0' }}
                                    />
                                </div>
                                <Upload
                                    name="avatar"
                                    listType="picture-card"
                                    className="avatar-uploader"
                                    showUploadList={false}
                                    accept="image/*"
                                    beforeUpload={(file) => {
                                        const maxSizeBytes = 10 * 1024 * 1024; // 10MB
                                        if (file.size > maxSizeBytes) {
                                            Modal.error({ title: '上传失败', content: '文件大小超出限制，请上传不超过10MB的文件' });
                                            // 阻止上传
                                            return false;
                                        }
                                        return true;
                                    }}
                                    customRequest={handleAvatarUpload}
                                >
                                    <Button icon={<CameraOutlined />} size="small">
                                        更换头像
                                    </Button>
                                </Upload>
                            </div>
                        </Col>

                        {/* 表单区域 */}
                        <Col xs={24} sm={16} md={18}>
                            <Form
                                form={form}
                                layout="vertical"
                                onFinish={handleSave}
                                autoComplete="off"
                                style={{ maxWidth: 600 }}
                            >
                                <Form.Item
                                    label="昵称"
                                    name="nick_name"
                                    rules={[
                                        { required: true, message: '请输入昵称' },
                                        { min: 2, max: 20, message: '昵称长度应在2-20个字符之间' }
                                    ]}
                                >
                                    <Input
                                        prefix={<UserOutlined />}
                                        placeholder="请输入昵称"
                                        size="large"
                                    />
                                </Form.Item>

                                <Form.Item
                                    label="手机号"
                                    name="phone"
                                    rules={[
                                        { required: true, message: '请输入手机号' }
                                        // { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
                                    ]}
                                >
                                    <Input
                                        prefix={<PhoneOutlined />}
                                        placeholder="请输入手机号"
                                        size="large"
                                        readOnly={true}
                                        addonAfter={
                                            <Button
                                                type="link"
                                                size="small"
                                                onClick={() => {
                                                    const currentPhone = form.getFieldValue('phone');
                                                    if (currentPhone) {
                                                        // 打开手机号修改弹窗，新手机号先为空，让用户输入
                                                        setVerificationModal({
                                                            visible: true,
                                                            type: 'phone',
                                                            step: 'old',
                                                            oldValue: currentPhone,
                                                            newValue: ''
                                                        });
                                                        verificationForm.resetFields();
                                                        setCountdown(0);
                                                    }
                                                }}
                                            >
                                                更换
                                            </Button>
                                        }
                                    />
                                </Form.Item>

                                <Form.Item
                                    label="邮箱"
                                    name="email"
                                    rules={[
                                        { required: true, message: '请输入邮箱' },
                                        { type: 'email', message: '请输入正确的邮箱格式' }
                                    ]}
                                >
                                    <Input
                                        prefix={<MailOutlined />}
                                        placeholder="请输入邮箱"
                                        size="large"
                                        readOnly={true}
                                        addonAfter={
                                            <Button
                                                type="link"
                                                size="small"
                                                onClick={() => {
                                                    const currentEmail = form.getFieldValue('email');
                                                    if (currentEmail) {
                                                        // 打开邮箱修改弹窗，新邮箱先为空，让用户输入
                                                        setVerificationModal({
                                                            visible: true,
                                                            type: 'email',
                                                            step: 'old',
                                                            oldValue: currentEmail,
                                                            newValue: ''
                                                        });
                                                        verificationForm.resetFields();
                                                        setCountdown(0);
                                                    }
                                                }}
                                            >
                                                更换
                                            </Button>
                                        }
                                    />
                                </Form.Item>

                                <Form.Item
                                    label="微信号"
                                    name="wechat_num"
                                >
                                    <Input
                                        prefix={<WechatOutlined />}
                                        placeholder="请输入微信号（选填）"
                                        size="large"
                                    />
                                </Form.Item>

                                <Form.Item>
                                    <Space>
                                        <Button
                                            type="primary"
                                            htmlType="submit"
                                            icon={<SaveOutlined />}
                                            loading={submitting}
                                            size="large"
                                        >
                                            保存修改
                                        </Button>
                                        <Button
                                            icon={<ReloadOutlined />}
                                            onClick={fetchPersonalInfo}
                                            size="large"
                                        >
                                            刷新数据
                                        </Button>
                                    </Space>
                                </Form.Item>
                            </Form>
                        </Col>
                    </Row>
                </Spin>

                <div style={{ marginTop: 24, padding: 16, background: '#f9f9f9', borderRadius: 8 }}>
                    <Paragraph type="secondary" style={{ margin: 0 }}>
                        <strong>说明：</strong>
                        <br />
                        • 个人资料修改后需要点击"保存修改"按钮才能生效
                        <br />
                        • 修改手机号或邮箱需要验证码验证
                        <br />
                        • 头像上传功能需要后端接口支持，目前仅为演示
                        <br />
                        • 带 * 号的字段为必填项
                    </Paragraph>
                </div>
            </Card>

            {/* 验证码验证弹窗 */}
            <Modal
                title={
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <SafetyCertificateOutlined />
                        {verificationModal.type === 'phone' ? '手机号验证' : '邮箱验证'}
                    </div>
                }
                open={verificationModal.visible}
                onCancel={closeVerificationModal}
                footer={null}
                width={500}
                destroyOnClose
            >
                <Steps
                    current={verificationModal.step === 'old' ? 0 : 1}
                    items={[
                        {
                            title: '验证旧号码',
                            description: `验证当前${verificationModal.type === 'phone' ? '手机号' : '邮箱'}`
                        },
                        {
                            title: '验证新号码',
                            description: `验证新的${verificationModal.type === 'phone' ? '手机号' : '邮箱'}`
                        }
                    ]}
                    style={{ marginBottom: 24 }}
                />

                <Form
                    form={verificationForm}
                    layout="vertical"
                    onFinish={verificationModal.step === 'old' ? verifyOldValue : verifyNewValue}
                >
                    {verificationModal.step === 'old' ? (
                        <>
                            <div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 6 }}>
                                <Text type="secondary">
                                    我们将向您的{verificationModal.type === 'phone' ? '手机号' : '邮箱'}
                                    <Text strong> {verificationModal.oldValue} </Text>
                                    发送验证码
                                </Text>
                            </div>

                            <Form.Item
                                label="验证码"
                                name="oldCode"
                                rules={[
                                    { required: true, message: '请输入验证码' },
                                    { len: 6, message: '验证码为6位数字' }
                                ]}
                            >
                                <Input
                                    placeholder="请输入6位验证码"
                                    maxLength={6}
                                    addonAfter={
                                        <Button
                                            type="link"
                                            size="small"
                                            disabled={countdown > 0}
                                            onClick={() => sendVerificationCode(
                                                verificationModal.type!,
                                                verificationModal.oldValue,
                                                false
                                            )}
                                        >
                                            {countdown > 0 ? `${countdown}s` : '发送验证码'}
                                        </Button>
                                    }
                                />
                            </Form.Item>
                        </>
                    ) : (
                        <>
                            <Form.Item
/*                                label={`新${verificationModal.type === 'phone' ? '手机号' : '邮箱'}`}
                                name="newValue"
                                rules={[
                                    { required: true, message: `请输入新${verificationModal.type === 'phone' ? '手机号' : '邮箱'}` },
                                    verificationModal.type === 'phone'
                                        ? { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
                                        : { type: 'email', message: '请输入正确的邮箱格式' }
                                ]}*/
                            >
                                <Input
                                    placeholder={`请输入新${verificationModal.type === 'phone' ? '手机号' : '邮箱'}`}
                                    onChange={(e) => {
                                        setVerificationModal(prev => ({
                                            ...prev,
                                            newValue: e.target.value
                                        }));
                                    }}
                                />
                            </Form.Item>

                            {verificationModal.newValue && (
                                <>
                                    <div style={{ marginBottom: 16, padding: 12, background: '#e6f7ff', borderRadius: 6 }}>
                                        <Text type="secondary">
                                            我们将向您的新{verificationModal.type === 'phone' ? '手机号' : '邮箱'}
                                            <Text strong> {verificationModal.newValue} </Text>
                                            发送验证码
                                        </Text>
                                    </div>

                                    <Form.Item
                                        label="验证码"
                                        name="newCode"
                                        rules={[
                                            { required: true, message: '请输入验证码' },
                                            { len: 6, message: '验证码为6位数字' }
                                        ]}
                                    >
                                        <Input
                                            placeholder="请输入6位验证码"
                                            maxLength={6}
                                            addonAfter={
                                                <Button
                                                    type="link"
                                                    size="small"
                                                    disabled={countdown > 0 || !verificationModal.newValue}
                                                    onClick={() => sendVerificationCode(
                                                        verificationModal.type!,
                                                        verificationModal.newValue,
                                                        true
                                                    )}
                                                >
                                                    {countdown > 0 ? `${countdown}s` : '发送验证码'}
                                                </Button>
                                            }
                                        />
                                    </Form.Item>
                                </>
                            )}
                        </>
                    )}

                    <Form.Item style={{ marginBottom: 0 }}>
                        <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
                            <Button onClick={closeVerificationModal}>
                                取消
                            </Button>
                            <Button
                                type="primary"
                                htmlType="submit"
                                loading={verificationLoading}
                                icon={<SendOutlined />}
                            >
                                {verificationModal.step === 'old' ? '验证并继续' : '确认修改'}
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default MyProfilePage;









